// get请求从searchConfig.url获取参数，post从searchConfig.body中获取参数
function param2obj(url: string) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    // 使用URLSearchParams更安全地解析参数
    const params = new URLSearchParams(search);
    const result: any = {};
    
    for (const [key, value] of params.entries()) {
        result[key] = value;
    }
    return result;
}

// 模拟10条固定用户数据
const List = [
    {
        id: '1',
        loginAccount: 'zihao.li',
        nickname: '李子豪',
        organization: '锐擎体育',
        phone: '13528051610',
        email: 'zihao.li@example.com',
        createTime: '2023-01-15 09:30:00',
        type: '企业',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '2',
        loginAccount: 'ljw',
        nickname: '刘举文',
        organization: '韶关学院',
        phone: '13800138002',
        email: 'ljw@qq.com',
        createTime: '2023-02-20 14:15:00',
        type: '企业',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '3',
        loginAccount: 'hutao',
        nickname: '胡桃',
        organization: '米哈游',
        phone: '13800138003',
        email: 'hutao@MiHoyo.com',
        createTime: '2023-03-10 11:45:00',
        type: '外部',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '4',
        loginAccount: 'wsh',
        nickname: '吴尚恒',
        organization: '韶关学院',
        phone: '13800138004',
        email: 'wsh@example.com',
        createTime: '2023-04-05 16:20:00',
        type: '企业',
        status: '禁用',
        del_flag: '0'
    },
    {
        id: '5',
        loginAccount: 'wh',
        nickname: '温涵',
        organization: '韶关学院',
        phone: '13800138005',
        email: 'wh@example.com',
        createTime: '2023-05-12 08:30:00',
        type: '外部',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '6',
        loginAccount: 'user006',
        nickname: '孙八',
        organization: '锐擎体育',
        phone: '13800138006',
        email: 'sunba@example.com',
        createTime: '2023-06-18 13:10:00',
        type: '企业',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '7',
        loginAccount: 'user007',
        nickname: '周九',
        organization: '韶关学院',
        phone: '13800138007',
        email: 'zhoujiu@example.com',
        createTime: '2023-07-22 10:55:00',
        type: '外部',
        status: '禁用',
        del_flag: '0'
    },
    {
        id: '8',
        loginAccount: 'user008',
        nickname: '吴十',
        organization: '锐擎体育',
        phone: '13800138008',
        email: 'wushi@example.com',
        createTime: '2023-08-30 17:40:00',
        type: '企业',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '9',
        loginAccount: 'user009',
        nickname: '郑一',
        organization: '韶关学院',
        phone: '13800138009',
        email: 'zhengyi@example.com',
        createTime: '2023-09-14 12:25:00',
        type: '外部',
        status: '正常',
        del_flag: '0'
    },
    {
        id: '10',
        loginAccount: 'user010',
        nickname: '王二',
        organization: '锐擎体育',
        phone: '13800138010',
        email: 'wanger@example.com',
        createTime: '2023-10-25 15:50:00',
        type: '企业',
        status: '正常',
        del_flag: '0'
    }
];


export default {
    getUserList: (searchConfig: any) => {
        console.log('Mock服务接收到的配置:', searchConfig)
        // limit默认是10，因为分页器默认也是一页10个
        const { loginAccount, organization, phone, type, page = 1, limit = 10 } = param2obj(searchConfig.url)
        
        let mockList = List.filter(item => {
            // 根据登录账号筛选
            if (loginAccount && item.loginAccount.indexOf(loginAccount) < 0) return false
            // 根据组织筛选
            if (organization && item.organization !== organization) return false
            // 根据手机号筛选
            if (phone && item.phone.indexOf(phone) < 0) return false
            // 根据用户类型筛选
            if (type && item.type !== type) return false
            // 根据del_flag筛选
            if (item.del_flag === '1') return false
            return true
        })

        const pageNum = parseInt(page)
        const pageSize = parseInt(limit)
        
        // 分页
        const pageList = mockList.filter((item, index) => index < pageSize * pageNum && index >= pageSize * (pageNum - 1))

        return {
            code: 200,
            msg: '获取成功',
            data: {
                list: pageList,
                count: mockList.length, // 数据总条数需要返回
            }
        }
    }
    /**
     * 删除用户
     * @param {number} id
     * @return {*}
     */
    ,
    deleteUser: (config: any) => {
        // 对于PUT请求，数据通常在请求体中而不是URL参数中
        let id;
        console.log('Mock服务接收到的配置:', config)
        if (config.body) {
            // 从请求体获取ID (MockJS使用body而不是data)
            if (typeof config.body === 'string') {
                try {
                    const parsedData = JSON.parse(config.body);
                    id = parsedData.id;
                    console.log('从body字符串中解析到ID:', id);
                } catch (e) {
                    console.log('body字符串JSON解析失败:', e);
                    // 如果JSON解析失败，可能是URL参数形式
                    const params = param2obj(config.url);
                    id = params.id;
                }
            } else if (typeof config.body === 'object') {
                id = config.body.id;
                console.log('从body对象中获取到ID:', id);
            }
        } else if (config.data) {
            // 从请求体获取ID
            if (typeof config.data === 'string') {
                try {
                    const parsedData = JSON.parse(config.data);
                    id = parsedData.id;
                    console.log('从data字符串中解析到ID:', id);
                } catch (e) {
                    console.log('data字符串JSON解析失败:', e);
                    // 如果JSON解析失败，可能是URL参数形式
                    const params = param2obj(config.url);
                    id = params.id;
                }
            } else if (typeof config.data === 'object') {
                id = config.data.id;
                console.log('从data对象中获取到ID:', id);
            }
        } else {
            // 为了兼容性，也尝试从URL参数获取ID
            const params = param2obj(config.url);
            id = params.id;
            console.log('从URL参数中获取到ID:', id);
        }
        
        console.log('Mock服务接收到的ID:', id)
        if (!id) {
            return {
                code: 500,
                msg: 'ID不能为空',
                data: null
            }
        } else {
            // 匹配对应id，将对应id的用户的del_flag设置为1
            const userIndex = List.findIndex(item => item.id === id);
            if (userIndex !== -1) {
                List[userIndex].del_flag = '1';
            } else {
                return {
                    code: 500,
                    msg: '未找到指定ID的用户',
                    data: null
                }
            }
        }
        return {
            code: 200,
            msg: '删除成功',
            data: {
                message: '删除成功'
            }
        }
    },

    /**
     * 添加用户
     * @param {object} user
     * @return {*}
     */
    createUser: (config: any) => { 
        console.log('创建用户配置:', config);
        let userData;
        // MockJS 将请求体数据存储在 body 中而不是 data 中
        if (config.body) {
            if (typeof config.body === 'string') {
                try {
                    userData = JSON.parse(config.body);
                    console.log('从body字符串中解析用户数据:', userData);
                } catch (e) {
                    return {
                        code: 500,
                        msg: '用户数据格式错误',
                        data: null
                    };
                }
            } else if (typeof config.body === 'object') {
                userData = config.body;
                console.log('从body对象中获取用户数据:', userData);
            }
        } else if (config.data) {
            if (typeof config.data === 'string') {
                try {
                    userData = JSON.parse(config.data);
                    console.log('从data字符串中解析用户数据:', userData);
                } catch (e) {
                    return {
                        code: 500,
                        msg: '用户数据格式错误',
                        data: null
                    };
                }
            } else if (typeof config.data === 'object') {
                userData = config.data;
                console.log('从data对象中获取用户数据:', userData);
            } else {
                return {
                    code: 500,
                    msg: '无效的用户数据格式',
                    data: null
                };
            }
        } else if (config.method && config.method.toLowerCase() === 'post') {
            // 尝试从URL参数中获取数据
            userData = param2obj(config.url);
            console.log('从URL参数中获取用户数据:', userData);
        } else {
            return {
                code: 500,
                msg: '缺少用户数据',
                data: null
            };
        }
        
        const { loginAccount, nickname, organization, phone, email, type } = userData;
        List.unshift({
            id: Date.now().toString(), // 使用时间戳生成唯一ID
            loginAccount,
            nickname,
            organization,
            phone,
            email,
            createTime: new Date().toLocaleString('zh-CN', { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-').replace(', ', ' '),
            type,
            status: '正常',
            del_flag: '0'
        })
        return {
            code: 200,
            msg: '添加成功',
            data: {
                message: '添加成功'
            }
        }
    },
    // 修改用户
    updateUser: (config: any) => { 
        const { id, loginAccount, nickname, organization, phone, email, type } = JSON.parse(config.body);
        
        // 查找用户并更新信息
        const userIndex = List.findIndex(item => item.id === id);
        if (userIndex !== -1) {
            // 更新用户信息
            List[userIndex].loginAccount = loginAccount;
            List[userIndex].nickname = nickname;
            List[userIndex].organization = organization;
            List[userIndex].phone = phone;
            List[userIndex].email = email;
            List[userIndex].type = type;
            
            return {
                code: 200,
                msg: '更新成功',
                data: {
                    message: '更新成功'
                }
            };
        } else {
            return {
                code: 500,
                msg: '未找到指定用户',
                data: null
            };
        }
    }

}